package iotwisp.school.user.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import iotwisp.base.jwt.JwtConfig;
import iotwisp.base.orm.BaseDao;
import iotwisp.base.util.JwtUtil;
import org.hibernate.Criteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import iotwisp.school.user.command.login_token.CreateLoginTokenDCmd;
import iotwisp.school.user.command.login_token.ExpireLoginTokenDCmd;
import iotwisp.school.user.command.login_token.LogoutLoginTokenDCmd;
import iotwisp.school.user.entity.LoginToken;
import iotwisp.school.user.qo.LoginTokenQO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

@Service
@Transactional
public class LoginTokenService extends BaseDao<LoginToken, LoginTokenQO> {

	@Autowired
	private JwtConfig jwtConfig;
	
    public LoginToken createLoginTokdn(CreateLoginTokenDCmd cmd) {
    	
    	String secret = jwtConfig.getSecret();
		log.info("s:{}", secret);
		Map<String, Object> claims = new HashMap<String, Object>();// 创建payload的私有声明（根据特定的业务需要添加，如果要拿这个做验证，一般是需要和jwt的接收方提前沟通好验证方式的）
		claims.put("clientType", cmd.getClientType());
		claims.put("clientId", cmd.getClientId());
		claims.put("loginName", cmd.getLoginName());
		claims.put("clientIp", cmd.getIp());

//		switch (cmd.getClientId()) {
//		case OperationConstants.CLIENT_ID_JGT_MERCHANT:
//			expire = jwtConfig.getJgtMerchantExpire();
//			break;
//		case OperationConstants.CLIENT_ID_JGT_PLATFORM:
//			expire = jwtConfig.getJgtPlatformExpire();
//			break;
//		default:
//			throw OperationException.getInstance(OperationException.CLIENT_TYPE_WRONG, "登录客户端类型有误");
//		}

		Date iat = new Date();

		String token = Jwts.builder().setClaims(claims).setSubject(cmd.getSubjectId()).setIssuedAt(iat)
				.setExpiration(cmd.getExpireDate()).compressWith(CompressionCodecs.DEFLATE)
				.signWith(SignatureAlgorithm.HS512, secret).compact();
		
		Claims claims2 = null;
		// 解析出jwt内容
		try {
			claims2 = JwtUtil.parseJWT(token, secret);
		} catch (Exception e) {
			e.printStackTrace();
		}

        //  创建登录令牌
    	LoginToken loginToken = new LoginToken();
    	loginToken.create(cmd, token);
        //  保存登录令牌
    	save(loginToken);
    	
        return loginToken;
    }

    public void expireLoginToken(ExpireLoginTokenDCmd cmd) {

        //  查出令牌
    	LoginTokenQO qo = new LoginTokenQO();
    	qo.setToken(cmd.getToken());
    	LoginToken loginToken = queryUnique(qo);
        //  过期
    	loginToken.expire(cmd);
    	update(loginToken);
    }

    public void logoutLoginToken(LogoutLoginTokenDCmd cmd) {

        //  查出令牌
    	LoginTokenQO qo = new LoginTokenQO();
    	qo.setToken(cmd.getToken());
    	LoginToken loginToken = queryUnique(qo);
        //  登出
    	loginToken.logout(cmd);
    	update(loginToken);
    }
    

	@Override
	protected Criteria buildCriteria(Criteria criteria, LoginTokenQO qo) {
		return criteria;
	}

	@Override
	protected Class<LoginToken> getEntityClass() {
		return LoginToken.class;
	}

}
